package com.lsh.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

@Slf4j
public class HttpClientUtils {


    public static String sendByJsonPost(String url, String data) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json; utf-8");
            // 设置参数
            StringEntity entity = new StringEntity(data, "UTF-8");
            entity.setContentType("application/json; utf-8");
            entity.setContentEncoding("UTF-8");
            httpPost.setEntity(entity);
            log.info("请求地址：" + url + "请求参数：" + data);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "UTF-8");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }


    /**
     * 模拟请求post请求
     *
     * @param url 请求地址
     * @param map 参数列表
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String sendByFormPost(String url, Map<String, String> map) {
        String body = "";

        try {
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (map != null) {
                for (Entry<String, String> entry : map.entrySet()) {
                    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue() + ""));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

            log.info("请求地址：" + url);
            log.info("请求参数：" + nvps.toString());

            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            CloseableHttpResponse response = client.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                body = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return body;
    }

    /**
     * 模拟请求get请求
     *
     * @param url      请求地址
     * @param map      参数列表
     * @param encoding 编码
     * @return
     * @throws URISyntaxException
     * @throws ClientProtocolException
     * @throws ParseException
     * @throws IOException
     */
    public static String sendByGet(String url, Map<String, String> map, String encoding) throws URISyntaxException, ClientProtocolException, IOException {
        String body = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        URIBuilder uriBuilder = new URIBuilder(url);
        if (map != null) {
            for (Entry<String, String> entry : map.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }
        URI uri = uriBuilder.build();
        log.info("请求地址：" + uri);
        HttpGet httpGet = new HttpGet(uri);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), encoding);
                log.info("返回结果：" + content);
                body = content;
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }

        return body;
    }


    public static void main(String[] args) throws ParseException, IOException, URISyntaxException {
//		String url="http://php.weather.sina.com.cn/iframe/index/w_cl.php";
//		Map<String, String> map = new HashMap<String, String>();
//		map.put("code", "js");
//		map.put("day", "0");
//		map.put("city", "上海");
//		map.put("dfc", "1");
//		map.put("charset", "utf-8");
//		String body = sendByPost(url, map,"utf-8");
//		System.out.println("交易响应结果：");
//		System.out.println(body);
//
//		System.out.println("-----------------------------------");
//
//		map.put("city", "北京");
//		body = sendByPost(url, map, "utf-8");
//		System.out.println("交易响应结果：");
//		System.out.println(body);
        Map<String, String> map = new HashMap<String, String>();

        //System.out.println(sendByGet("https://wx.vibeac.com/bizcard/openapi/invoice/detail?invoiceId=594cd03d5002660ad8b51657&appCode=MPH&id=5951d4a2e905720a1991d3a4&type=2", map, "UTF-8"));
        // System.out.println(sendByGet("http://wx.vibeac.com/bizcard/card/invoice/invoiceInfoList.do?appCode=MPH&id=5951d4a2e905720a1991d3a4&type=2", map, "UTF-8"));
    }
}